package sk.naive.talker.command;

import sk.naive.talker.*;
import sk.naive.talker.adapter.TagConsts;
import sk.naive.talker.message.*;
import sk.naive.talker.util.*;
import sk.naive.talker.props.*;

import java.rmi.RemoteException;
import java.util.Iterator;
import java.util.Date;
import java.text.SimpleDateFormat;

/**
 *
 * @author <a href="mailto:virgo@naive.deepblue.sk">Richard "Virgo" Richter</a>
 * @version $Revision: 1.18 $ $Date: 2005/01/19 22:41:27 $
 */
public abstract class ReviewCommand extends AbstractCommand {
	public static final String UPROP_REVIEW_PAGER = "reviewPager";
	public static final SimpleDateFormat sdf = new SimpleDateFormat("<HH:mm> ");
	public static final SimpleDateFormat sdfx = new SimpleDateFormat("<dd.MM. HH:mm> ");

	public void exec()
		throws CommandException, RemoteException, PropertyStoreException
	{
		PropertyStore store = getReviewStore(user, params);
		ctxSet(DefaultMessageFactory.CTXKEY_VAL, store.getProperties());
		Buffer review = (Buffer) store.getProperties().get(getReviewPropertyName());
		if (review == null || review.size() == 0) {
			sendHelper().sendMessage(user, getReviewEmptyMessageKey());
		} else {
			Iterator i = review.iterator();
			String lang = user.getLang();
			StringBuilder sb = new StringBuilder();
			Date cutDate = new Date(System.currentTimeMillis() - (Consts.MINUTE_MILLIS * Consts.DAY_MINUTES));
			sb.append(getString(getReviewHeadMessageKey(), user.getProperties()));
			while (i.hasNext()) {
				Message m = (Message) i.next();
				if (haveToPrintTimestamp()) {
					Date mesgDate = m.getDate();
					if (mesgDate.after(cutDate)) {
						sb.append(sdf.format(mesgDate));
					} else {
						sb.append(sdfx.format(mesgDate));
					}
				}
				sb.append(m.get(lang));
			}
			sb.append(getString(getReviewTailMessageKey(), user.getProperties()));
			if (BooleanProperty.booleanValue((String) user.get(UPROP_REVIEW_PAGER))) {
				sb.append(Utils.tag(TagConsts.PAGING));
			}
			user.send(sb.toString());
		}
	}

	protected boolean haveToPrintTimestamp() {
		return true;
	}

	public abstract PropertyStore getReviewStore(User user, String params);

	public abstract String getReviewPropertyName();

	public abstract String getReviewEmptyMessageKey();
	public abstract String getReviewHeadMessageKey();
	public abstract String getReviewTailMessageKey();
}
